package cn.btks.backstagemanage.unit.service.impl;

import cn.btks.backstagemanage.division.pojo.City;
import cn.btks.backstagemanage.division.service.CityService;
import cn.btks.backstagemanage.menu.pojo.Menu;
import cn.btks.backstagemanage.unit.pojo.Unit;
import cn.btks.backstagemanage.unit.repository.UnitRepository;
import cn.btks.backstagemanage.unit.service.UnitService;
import cn.btks.commonserver.pojo.PageList;
import cn.btks.commonserver.result.ResultState;
import cn.btks.commonserver.result.StateInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @Author lijun
 * @Date 2021/1/13 13:04
 */
@Service
@Transactional
public class UnitServiceImpl implements UnitService {

    @Autowired
    UnitRepository unitRepository;

    @Autowired
    CityService cityService;

    @Override
    public Unit findById(Long id) {
        Optional<Unit> optional = unitRepository.findById(id);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;
    }

    @Override
    public List<Unit> findAll() {
        return unitRepository.findAll();
    }

    @Override
    public ResultState findPageList(Integer pageNumber, Integer pageSize, String unitName) {
        PageRequest pageRequest = PageRequest.of(pageNumber - 1, pageSize);
        Specification<Unit> specification = new Specification<Unit>() {
            @Override
            public Predicate toPredicate(Root<Unit> root,
                                         CriteriaQuery<?> criteriaQuery,
                                         CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (!StringUtils.isEmpty(unitName)) {
                    predicates.add(criteriaBuilder.like(root.get("unitName"),
                            "%" + unitName + "%"));
                }
                Predicate[] predicates1 = new Predicate[predicates.size()];
                return criteriaBuilder.and(predicates.toArray(predicates1));
            }
        };
        Page<Unit> configPage = unitRepository.findAll(specification, pageRequest);
        if(configPage.getTotalElements() > 0){
            PageList pageList = new PageList();
            pageList.setResult(configPage.getContent());
            pageList.setPageNum(configPage.getTotalPages());
            pageList.setTotalCount(configPage.getTotalElements());
            return new ResultState(StateInfo.FIND_OK.getCode(), StateInfo.FIND_OK.getMsg(), pageList);
        }
        return new ResultState(StateInfo.FIND_NULL.getCode(), StateInfo.FIND_NULL.getMsg());
    }

    @Override
    public ResultState findPageList1(Integer pageNumber, Integer pageSize, String unitName, Long cityId) {
        PageRequest pageRequest = PageRequest.of(pageNumber - 1, pageSize);
        Specification<Unit> specification = new Specification<Unit>() {
            @Override
            public Predicate toPredicate(Root<Unit> root,
                                         CriteriaQuery<?> criteriaQuery,
                                         CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (!StringUtils.isEmpty(unitName)) {
                    predicates.add(criteriaBuilder.like(root.get("unitName"),
                            "%" + unitName + "%"));
                }
                if (cityId != null) {
                    predicates.add(criteriaBuilder.equal(root.get("cityId"), cityId));
                }
                Predicate[] predicates1 = new Predicate[predicates.size()];
                return criteriaBuilder.and(predicates.toArray(predicates1));
            }
        };
        Page<Unit> configPage = unitRepository.findAll(specification, pageRequest);
        if(configPage.getTotalElements() > 0){
            PageList pageList = new PageList();
            pageList.setResult(configPage.getContent());
            pageList.setPageNum(configPage.getTotalPages());
            pageList.setTotalCount(configPage.getTotalElements());
            return new ResultState(StateInfo.FIND_OK.getCode(), StateInfo.FIND_OK.getMsg(), pageList);
        }
        return new ResultState(StateInfo.FIND_NULL.getCode(), StateInfo.FIND_NULL.getMsg());
    }

    @Override
    public ResultState save(Unit unit) {
        if(unit.getIsCity() == 1){
            City city = cityService.findById(unit.getCityId());
            unit.setCityCode(city.getCode());
        }
        Unit unit1 = unitRepository.save(unit);
        return unit1 != null ? new ResultState(StateInfo.SAVE_OK.getCode(), StateInfo.SAVE_OK.getMsg(), unit1) :
                new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
    }

    @Override
    public ResultState update(Unit unit) {
        if(unit.getId() != null){
            Optional<Unit> optional = unitRepository.findById(unit.getId());
            if(optional.isPresent()){
                if(unit.getIsCity() == 1){
                    City city = cityService.findById(unit.getCityId());
                    unit.setCityCode(city.getCode());
                }
                Unit unit1 = unitRepository.save(unit);
                return unit1 != null ? new ResultState(StateInfo.SAVE_OK.getCode(), StateInfo.SAVE_OK.getMsg(), unit1) :
                        new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
            }
        }
        return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
    }

    @Override
    public ResultState delete(Long id) {
        Optional<Unit> optional = unitRepository.findById(id);
        if(optional.isPresent()){
            int result = unitRepository.deleteUnitById(id);
            return result > 0 ? new ResultState(StateInfo.DELETE_OK.getCode(), StateInfo.DELETE_OK.getMsg(), result):
                    new ResultState(StateInfo.DELETE_ERROR.getCode(), StateInfo.DELETE_ERROR.getMsg());
        }
        return new ResultState(StateInfo.DELETE_ERROR_2.getCode(), StateInfo.DELETE_ERROR_2.getMsg());
    }
}
